/* user.c */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "user.h"
#include "protocol.h"

#define FALSE 0
#define TRUE 1

user_database_t *user_database_open(const char * path){
	FILE *fp = NULL;
	user_database_t *file;
	if((fp = fopen(path, "r"))== NULL ){
		return NULL;
	}
	if((file = (user_database_t *)malloc(sizeof(user_database_t))) == NULL){
		fclose(fp);
		return NULL;
	}
	file->user_file = fp;
	return file;
}

int user_database_close(user_database_t * base){
	fclose(base->user_file);
	free(base);
	return 0;
}


int check_user(user_database_t *base, const char *nm, const char *pw){
	FILE *fp = NULL;
	char buffer[256];
	int findit = FALSE;
	if((fp = base->user_file) == NULL)
		return SERVER_BUSY;
	fseek(fp,0,SEEK_SET);
	
	while( fgets(buffer, 256, fp) != NULL){
		char *name;
		char *pwd;

		if((name = strstr(buffer,"\t")) != NULL){
			*name = '\0';
			name += 1;
		}else continue;
		if((pwd = strstr(name,"\t")) != NULL){
			*pwd = '\0';
			pwd += 1;
		}else continue;
		pwd[strlen(pwd) -1 ] = '\0';
		if(strcmp(name, nm) == 0){
			findit =TRUE;
			if(strcmp(pwd,pw) == 0){
				return atoi(buffer);
			}else{
				return INVALID_PWD;
			}
		}
	}
	return INVALID_USR;
}
/*

int find_name_by_id(user_database_t *base, int id, char *buf){
	FILE *fp = NULL;
	char buffer[256];
	if((fp = base->user_file) == NULL)
		return -1;
	fseek(fp,0,SEEK_SET);
	
	while( fgets(buffer, 256, fp) != NULL){
		char *name;
		char *pwd;
		
		if((name = strstr(buffer,"\t")) != NULL){
			*name = '\0';
			name += 1;
		}else continue;
		if((pwd = strstr(name,"\t")) != NULL){
			*pwd = '\0';
			pwd += 1;
		}else continue;
		pwd[strlen(pwd) -1 ] = '\0';
		if(atoi(buffer) == id){
			strcpy(buf, name);
			return 0;
		}
	}
	return -1;
}
*/

